//
// Created by de on 3/29/21.
//

#include "SqlSqliteDao.h"
using namespace sqlite_orm;
#define DATATABLE "WorkResult"

//#include "spdlog/spdlog.h"
const static std::string DataBasePath = "/home/fshs/my_data/db.sqlite";
using namespace std;
//CREATE TABLE  WorkResult ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'VisionConsumerTime' REAL NOT NULL,'VisionDepthBias' REAL NOT NULL,
//        'ForceConsumerTime' REAL NOT NULL ,'Vaild' boolean not null, 'Date' TEXT not null );
auto storge = sqlite_orm::make_storage(DataBasePath,
    make_table("WorkResult",
    make_column("id", &WorkResult::id, autoincrement(), primary_key()),
    make_column("VisionConsumerTime", &WorkResult::VisionConsumerTime),
    make_column("VisionDepthBias", &WorkResult::VisionDepthBias),
    make_column("ForceConsumerTime", &WorkResult::ForceConsumerTime),
    make_column("Vaild", &WorkResult::Vaild),
    make_column("datetime", &WorkResult::datetime),
    make_column("ErrorMessage", &WorkResult::ErrorMessage)
    ));


SqlSqliteDao::SqlSqliteDao() {

}


bool SqlSqliteDao::connect() {

    storge.sync_schema();
    storge.open_forever();
    return storge.is_opened() ;
}

void SqlSqliteDao::selectProperty(const std::string &Property, std::string &result) {

}



bool SqlSqliteDao::checkTableExist() {
    bool IsExist = storge.table_exists(DATATABLE);
//    spdlog::info("checkTableExist: "+IsExist);
    return IsExist;
}

bool SqlSqliteDao::insertObject( WorkResult &workResult1) {
    bool  ret = true;
    storge.begin_transaction();

    try {
        std::string t_datatime  = storge.select(datetime("now", "localtime")).front();
        workResult1.setDateTime(t_datatime);

        storge.insert(workResult1);


        storge.commit();

    }catch (std::exception &e){
        spdlog::error(e.what());
        storge.rollback();
        ret = false;
    }

    return ret;
}

void SqlSqliteDao::removeAll() {
    storge.begin_transaction();
    storge.remove_all<WorkResult>();
    storge.commit();

//    spdlog::warn("removeAll .... ");


}

std::vector<WorkResult> SqlSqliteDao::getAll() {
    return storge.get_all<WorkResult>();
}

double SqlSqliteDao::count(const std::string &property) {
    //select * from WorkResult
    return storge.count<WorkResult>();;
}

void SqlSqliteDao::disconnect() {
//    spdlog::warn("SqLite3 disconnect  .... ");
}

void SqlSqliteDao::remove(const std::string &property, const std::string &value) {

}



double SqlSqliteDao::average(const string &property) {

    double  temp = -1;
    try{
        if (property.compare("ForceConsumerTime"))
        {
            temp = storge.avg(&WorkResult::ForceConsumerTime);
        }else if(property.compare("VisionConsumerTime")){
            temp = storge.avg(&WorkResult::VisionConsumerTime);
        } else if(property.compare("VisionDepthBias")) {
            temp = storge.avg(&WorkResult::VisionDepthBias);
        }

     }catch(...) {
//        spdlog::error("throw Error code ");
    }


    return temp;
}
